<html>
<head>
	<title>Diagram Model</title>
	<script type="text/javascript" src="js/mxClient.js"></script>
	<script type="text/javascript" src="js/jquery-1.10.2.min.js" ></script>
	<script type="text/javascript">
		var vertexStyle = 'shape=ellipse;strokeWidth=2;fillColor=#ffffff;strokeColor=#0099CC;gradientColor=#0099CC;fontColor=black;fontStyle=1;spacingTop=14;';
		var edgeStyle = 'strokeWidth=3;endArrow=block;endSize=2;endFill=1;strokeColor=black;rounded=1;';

		function uuid() {
			var s = [];
			var hexDigits = "0123456789abcdef";
			for (var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
			s[8] = s[13] = s[18] = s[23] = "-";
		
			var uuid = s.join("");
			return uuid;
		}

		var index = 1;
		window.states = [];
		var state_s = null;
		window.links = [];

		function main(container){
			if (!mxClient.isBrowserSupported()){
				mxUtils.error('Browser is not supported!', 200, false);
			}
			else{
				mxGraph.prototype.dblClick = function(evt, cell){
					if (cell != null){
						if (this.model.isVertex(cell)){
							// alert("Double Click in Vertex: " + cell.state.name);
							state_s = cell;
							$('#stateId').val(cell.state.id);
							$('#stateName').val(cell.state.name);
							$('#stateType').val(cell.state.type);
							$('#stateDes').val(cell.state.description);
						}
						else{
							// alert("Double Click in Edge!");
						}
					}
					else{
						// alert("Double Click in Panel!");
					}
					// mxGraphDblClick.call(this, evt, cell);
				};

				mxConnectionHandler.prototype.connectImage = new mxImage('images/connector.gif', 16, 16);

				window.graph = new mxGraph(container);
				
				graph.setEnabled(true);
				graph.setPanning(true);
				graph.setConnectable(true);
				graph.setCellsResizable(false);
				graph.setCellsDisconnectable(false);
				graph.swimlaneNesting = false;
				graph.dropEnabled = true;
				graph.setAllowDanglingEdges(false);
				graph.setMultigraph(false);
				graph.setAllowLoops(true);
				graph.setTolerance(20);

				var content = document.getElementById('content');

				window.wnd_state = new mxWindow('State Inforamtion', content, 800, 0, 300, 300, true, true);
				window.wnd_state.setScrollable(false);
				window.wnd_state.setResizable(true);
				window.wnd_state.setVisible(true);
				
				var keyHandler = new mxKeyHandler(graph);
				
				var graphs = [];

				var parent = graph.getDefaultParent();
				var v1, v2, e1;

				mxEvent.addListener(document, 'keydown', function(evt){
					var source = mxEvent.getSource(evt);
					if (evt.keyCode == 46){
						var cells = graph.getSelectionCells();
						graph.removeCells(cells);
					}
				});

				graph.addListener(mxEvent.ADD_CELLS, function(sender, evt){
					var cells = evt.getProperty('cells');
					for (var i = 0; i < cells.length; i++){
						var cell = cells[i];
						if (this.model.isEdge(cell)){
							window.links.push({
								from : cell.source.state.id,
								to : cell.target.state.id
							});
							// alert('Edge Added! Source: [' + cell.source.state.name + '], Target: [' + cell.target.state.name + ']');
							cell.style = edgeStyle;
							cell.from = cell.source.state.id;
							cell.to = cell.target.state.id;
						}
						if (this.model.isVertex(cell)){
							// alert('Vertex Added! Name: [' + cell.state.name + ']');
						}
					}
				});
				
				graph.addListener(mxEvent.REMOVE_CELLS, function(sender, evt){
					var cells = evt.getProperty('cells');
					for (var i = 0; i < cells.length; i++){
						var cell = cells[i];
						if (this.model.isEdge(cell)){
							for(var j = 0; j < window.links.length; j++){
								if(window.links[j].from == cell.from && window.links[j].to == cell.to){
									window.links.splice(j, 1);
								}
							}
							// alert('Edge Removed!');
						}
						if (this.model.isVertex(cell)){
							for(var j = 0; j < window.states.length; j++){
								if (window.states[j].state.id == cell.state.id){
									window.states.splice(j, 1);
								}
							}
							// alert('Vertex Removed!');
						}
					}
				});
				graphs.push(graph);
				var state = graph.view.getState(e1);
			}

			var graphF = function(evt){
				var x = mxEvent.getClientX(evt);
				var y = mxEvent.getClientY(evt);
				var elt = document.elementFromPoint(x, y);
				
				for (var i = 0; i < graphs.length; i++){
					if (mxUtils.isAncestorNode(graphs[i].container, elt)){
						return graphs[i];
					}
				}
				
				return null;
			};
			
			var funct = function(graph, evt, target, x, y){
				var v_cell = graph.insertVertex(parent, null, 'State' + index, x, y, 100, 50, vertexStyle);
				var state = {
					id : uuid(),
					name : 'State' + index,
					type : "basic",
					description : ""
				};
				v_cell['state'] = state;
				window.states.push(v_cell);
				index ++;
			};
			
			var img = document.getElementById('imgState');
			// document.body.appendChild(img);
			
			var dragElt = document.createElement('div');
			dragElt.style.border = 'dashed black 1px';
			dragElt.style.width = '100px';
			dragElt.style.height = '50px';

			var ds = mxUtils.makeDraggable(img, graphF, funct, dragElt, null, null, graph.autoscroll, true);
			ds.isGuidesEnabled = function(){
				return graph.graphHandler.guidesEnabled;
			};
			
			ds.createDragElement = mxDragSource.prototype.createDragElement;

			$('#stateConfirm').click(function(e){
				if(state_s != null){
					state_s.state.id = $('#stateId').val();
					state_s.state.name = $('#stateName').val();
					state_s.state.type = $('#stateType').val();
					state_s.state.description = $('#stateDes').val();
					state_s.value = $('#stateName').val();
					graph.refresh(state_s)
				}
			});

			$('#btTest').click(function(e){
				loadJSON(format2JSON());
			});
		};

		function format2JSON(){
			var behaviors = {
				states : [],
				trisition : []
			};
			for(var i = 0; i < window.states.length; i++){
				var state = {};
				state['id'] = window.states[i].state.id;
				state['name'] = window.states[i].state.name;
				state['type'] = window.states[i].state.type;
				state['description'] = window.states[i].state.description;
				behaviors.states.push(state);
			}
			for(var i = 0; i < window.links.length; i++){
				var link = {};
				link['from'] = window.links[i].from;
				link['to'] = window.links[i].to;
				behaviors.trisition.push(link);
			}
			return JSON.stringify(behaviors);
		}

		function loadJSON(strjson){
			window.graph.removeCells(window.graph.getChildVertices(window.graph.getDefaultParent()));
			jsBahavior = JSON.parse(strjson);
			var parent = window.graph.getDefaultParent();
			for (var i = 0; i < jsBahavior.states.length; i++){
				var v_cell = window.graph.insertVertex(parent, null, jsBahavior.states[i].name, 20 + i*120, 20, 100, 50, vertexStyle);
				v_cell['state'] = {
					id : jsBahavior.states[i].id,
					name : jsBahavior.states[i].name,
					type : jsBahavior.states[i].type,
					description : jsBahavior.states[i].description
				}
				window.states.push(v_cell);
			}
			for (var i = 0; i < jsBahavior.trisition.length; i++){
				
			}
		}
	</script>
</head>

<body onload="main(document.getElementById('graphContainer'))">
	<div id="graphContainer"
		style="overflow:hidden;width:1000px;height:400px;background:url('images/grid.gif')">
	</div>
	<img id="imgState" src="images/modelState.png" width="100px" height="70px" />
	<input id="btTest" type="button" value="test" />
	<div id="content">
		<table>
			<tbody>
				<tr>
					<td>ID</td>
					<td><input id="stateId" type="input" /></td>
				</tr>
				<tr>
					<td>Name</td>
					<td><input id="stateName" type="input" /></td>
				</tr>
				<tr>
					<td>type</td>
					<td>
						<select id="stateType">
							<option value="basic" >basic</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>description</td>
					<td><textarea id="stateDes" rows="10" cols="23" ></textarea></td>
				</tr>
			</tbody>
		</table>
		<div style="text-align: center">
			<input id="stateConfirm" type="button" value="confirm" />
		</div>
	</div>
</body>
</html>
